package de.unibi.comet.fa;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;

public class Alphabet implements Iterable<Character> {
	private char[] chars;
	private int[] charIndices;

	public Alphabet(Collection<Character> l) {
		List<Character> sortedList = new ArrayList<Character>(l);
		Collections.sort(sortedList);
		chars = new char[l.size()];
		charIndices = new int[256];
		Arrays.fill(charIndices, -1);
		int i=0;
		for (char c : sortedList) {
			chars[i]=c;
			charIndices[c]=i;
			++i;
		}
	}
	
	private class ArrayIterator implements Iterator<Character> {
		private int i;
		ArrayIterator() { i=0; }
		public boolean hasNext() { return i<chars.length; }
		public Character next() {
			try {
				return chars[i++];
			} catch (IndexOutOfBoundsException e) {
				throw new NoSuchElementException();
			}
		}
		public void remove() { throw new UnsupportedOperationException(); }
	}
	
	public Iterator<Character> iterator() { return new ArrayIterator(); }
	
	public int size() { return chars.length; }
	
	public char get(int index) { return chars[index]; }
	public int getIndex(char c) { return charIndices[c]; }
	public boolean contains(char c) { return charIndices[c]>=0; }

	@Override
	public boolean equals(Object obj) {
		if (!(obj instanceof Alphabet)) return false;
		return Arrays.equals(chars, ((Alphabet)obj).chars);
	}

	@Override
	public int hashCode() {
		return Arrays.hashCode(chars);
	}
	
}
